package cc.linker.steplink.crm.commons.integral;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: CKQ
 * @DateTime: 2020/8/18 9:27
 * @Description: TODO
 */
@Slf4j
@Service
public class IntegralRequest {
    @Value("${system.scrm.integralAppId}")
    private String integralAppId;
    @Value("${system.scrm.integralUrl}")
    private String integralUrl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HttpService httpService;

    /**
     * @Description：通用的接口请求
     * @DateTime：2020/8/18 9:36
     * @Params：active 方法
     * @Return：
     */
    public Map<String,Object> doRequest(String key, Map<String, Object> params) {
        try {
            InterfaceInfo interfaceInfo = ActiveConfig.getInterfaceInfo(key);
            if (interfaceInfo == null) {
                throw GlobalException.build("请求方法不能为空");
            }
            Map<String, String> headerMap = this.initHeader();
            String result = "";
            switch (interfaceInfo.getMode()) {
                case "get":
                    result = httpService.doGet(integralUrl + interfaceInfo.getMethod(), params, headerMap);
                    break;
                case "post":
                    result = httpService.doPost(integralUrl + interfaceInfo.getMethod(), JSON.toJSONString(params), headerMap);
                    break;
                case "delete":
                    result = httpService.doDelete(integralUrl + interfaceInfo.getMethod(), params, headerMap);
                    break;
                case "put":
                    result = httpService.doPut(integralUrl + interfaceInfo.getMethod(), JSON.toJSONString(params), headerMap);
                    break;
                default:
                    break;
            }
            if (StringUtils.isEmpty(result)) {
                LOGGER.error("请求中台积分服务---请求地址：integralUrl--" + integralUrl + "  "
                        + JSON.toJSONString(interfaceInfo) + "请求参数:" + JSON.toJSONString(params)
                +"请求header="+JSON.toJSONString(headerMap));
                throw GlobalException.build("请求积分中台服务失败，请重试！");
            } else {
                Map resultMap = (Map) JSON.parse(result);
                if (resultMap != null) {
                    if (resultMap.get("code").toString().equals("200")) {
                        if("get-customers-score".equals(key)){
                            return  resultMap;
                        }
                        if (resultMap.containsKey("data")) {
                            return (Map) resultMap.get("data");
                        } else {
                            return new HashMap();
                        }
                    } else {
                        throw GlobalException.build(resultMap.get("msg").toString());
                    }
                } else {
                    LOGGER.info("请求积分中台服务失败，请重试：request--url" + integralUrl);
                    LOGGER.info("请求积分中台服务失败，请重试：request--parmas" +  JSON.toJSONString(params));
                    LOGGER.info("请求积分中台服务失败，请重试：result" + result);
                    throw GlobalException.build("请求积分中台服务失败，请重试");
                }
            }
        } catch (Exception ex) {
            LOGGER.error("请求中台积分服务错误：", ex);
            throw GlobalException.build("请求积分中台服务失败，请重试");
        }
    }

    /**
     * @Description：生成header
     * @DateTime：2020/8/18 9:43
     * @Params：customerId 用户ID 传则需要组装authToken，不传则不用组装
     * @Return：
     */
    private Map<String, String> initHeader() {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("appId", integralAppId);
        headerMap.put("Content-Type", "application/json");
        return headerMap;
    }
}
